<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>快递驿站管理系统 - 前端测试</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        body {
            padding-top: 60px;
        }
        .container {
            max-width: 1200px;
        }
        .tab-content {
            margin-top: 20px;
            padding: 20px;
            border: 1px solid #dee2e6;
            border-top: none;
            border-radius: 0 0 0.375rem 0.375rem;
        }
        .form-group {
            margin-bottom: 1rem;
        }
        .btn-group {
            margin-bottom: 1rem;
        }
        .status-badge {
            padding: 0.35em 0.65em;
            font-size: 0.75em;
            font-weight: 700;
            line-height: 1;
            color: #fff;
            background-color: #6c757d;
            border-radius: 0.375rem;
        }
        .status-badge.in-storage {
            background-color: #198754;
        }
        .status-badge.out-storage {
            background-color: #0d6efd;
        }
        .status-badge.signed {
            background-color: #6f42c1;
        }
        .status-badge.other {
            background-color: #6c757d;
        }
        .login-container {
            max-width: 400px;
            margin: 80px auto;
            padding: 20px;
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            background-color: #fff;
        }
        .navbar-nav .nav-item .nav-link.disabled {
            color: rgba(255,255,255,.5);
            pointer-events: none;
            cursor: default;
        }
    </style>
</head>
<body>
    <!-- 登录表单 - 默认显示 -->
    <div id="loginFormContainer" class="login-container">
        <h2 class="text-center mb-4">用户登录</h2>
        <div id="loginMessage" class="text-danger mb-3"></div>
        <form id="loginForm">
            <div class="mb-3">
                <label for="loginUsername" class="form-label">用户名</label>
                <input type="text" class="form-control" id="loginUsername" placeholder="请输入用户名" required>
            </div>
            <div class="mb-3">
                <label for="loginPassword" class="form-label">密码</label>
                <input type="password" class="form-control" id="loginPassword" placeholder="请输入密码" required>
            </div>
            <button type="button" class="btn btn-primary w-100" onclick="submitLoginForm()">登录</button>
        </form>
        <div class="text-center mt-3">
            <p class="text-muted">系统默认账户：</p>
            <p>管理员: admin / admin123</p>
            <p>快递员: courier1 / courier123</p>
        </div>
    </div>

    <!-- 系统内容 - 登录后显示 -->
    <div id="systemContent" style="display: none;">
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
            <div class="container">
                <a class="navbar-brand" href="#">快递驿站管理系统</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav">
                        <li class="nav-item">
                            <a class="nav-link active" aria-current="page" href="#packageList">快递管理</a>
                        </li>
                     
                    </ul>
                    <div class="navbar-nav ms-auto">
                        <li class="nav-item">
                            <span class="nav-link" id="currentUser">未登录</span>
                        </li>
                        <li class="nav-item">
                            <button class="btn btn-danger" onclick="logout()">退出登录</button>
                        </li>
                    </div>
                </div>
            </div>
        </nav>

        <div class="container">
            <!-- 快递管理部分 -->
            <div id="packageManagement" class="mb-5">
                <h2>快递包裹管理</h2>
                
                <!-- 操作按钮组 -->
                <div class="btn-group" role="group">
                    <button type="button" class="btn btn-primary" onclick="showPackageForm()">新增快递</button>
                    <button type="button" class="btn btn-success" onclick="refreshPackageList()">刷新列表</button>
                </div>
            
            <!-- 查询表单 -->
            <div class="row mt-3">
                <div class="col-md-4">
                    <div class="input-group">
                        <input type="text" id="trackingNumberQuery" class="form-control" placeholder="输入快递单号查询">
                        <button class="btn btn-outline-secondary" type="button" onclick="searchByTrackingNumber()">查询</button>
                    </div>
                </div>
                <div class="col-md-3">
                    <select id="statusQuery" class="form-select" onchange="searchByStatus()">
                        <option value="">全部状态</option>
                        <option value="已入库">已入库</option>
                        <option value="已出库">已出库</option>
                        <option value="已签收">已签收</option>
                    </select>
                </div>
            </div>
            
            <!-- 快递列表 -->
            <div id="packageList" class="mt-4">
                <h3>快递列表</h3>
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>快递单号</th>
                            <th>寄件人</th>
                            <th>收件人</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>签收时间</th>
                            <th>签收人</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="packageTableBody">
                        <!-- 快递数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
                <div id="packagePagination" class="pagination justify-content-center mt-3">
                    <!-- 分页控件将通过JavaScript动态加载 -->
                </div>
            </div>
            
            <!-- 新增/编辑快递表单 -->
            <div id="packageForm" class="mt-4" style="display: none;">
                <h3><span id="formTitle">新增快递</span></h3>
                <form id="packageFormData" class="row g-3">
                    <input type="hidden" id="packageId">
                    <div class="col-md-6">
                        <label for="trackingNumber" class="form-label">快递单号</label>
                        <input type="text" class="form-control" id="trackingNumber" required>
                    </div>
                    <div class="col-md-6">
                        <label for="status" class="form-label">状态</label>
                        <select class="form-select" id="status" required>
                            <option value="已入库">已入库</option>
                            <option value="已出库">已出库</option>
                            <option value="已签收">已签收</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label for="senderName" class="form-label">寄件人姓名</label>
                        <input type="text" class="form-control" id="senderName">
                    </div>
                    <div class="col-md-6">
                        <label for="senderPhone" class="form-label">寄件人电话</label>
                        <input type="text" class="form-control" id="senderPhone">
                    </div>
                    <div class="col-md-6">
                        <label for="receiverName" class="form-label">收件人姓名</label>
                        <input type="text" class="form-control" id="receiverName" required>
                    </div>
                    <div class="col-md-6">
                        <label for="receiverPhone" class="form-label">收件人电话</label>
                        <input type="text" class="form-control" id="receiverPhone" required>
                    </div>
                    <div class="col-md-12">
                        <label for="receiverAddress" class="form-label">收件人地址</label>
                        <input type="text" class="form-control" id="receiverAddress">
                    </div>
                    <div class="col-md-12">
                        <label for="remark" class="form-label">备注</label>
                        <textarea class="form-control" id="remark" rows="3"></textarea>
                    </div>
                    <div class="col-md-12">
                        <button type="button" class="btn btn-primary" onclick="submitPackageForm()">提交</button>
                        <button type="button" class="btn btn-secondary" onclick="hidePackageForm()">取消</button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- 用户管理部分 -->
        <div id="userManagement">
            <h2>用户管理</h2>
            
            <!-- 操作按钮组 -->
            <div class="btn-group" role="group">
                <button type="button" class="btn btn-primary" onclick="showUserForm()">新增用户</button>
                <button type="button" class="btn btn-success" onclick="refreshUserList()">刷新列表</button>
            </div>
            
            <!-- 用户列表 -->
            <div id="userList" class="mt-4">
                <h3>用户列表</h3>
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>真实姓名</th>
                            <th>电话</th>
                            <th>角色</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="userTableBody">
                        <!-- 用户数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
            
            <!-- 新增/编辑用户表单 -->
            <div id="userForm" class="mt-4" style="display: none;">
                <h3><span id="userFormTitle">新增用户</span></h3>
                <form id="userFormData" class="row g-3">
                    <input type="hidden" id="userId">
                    <div class="col-md-6">
                        <label for="username" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="username" required>
                    </div>
                    <div class="col-md-6">
                        <label for="password" class="form-label">密码</label>
                        <input type="password" class="form-control" id="password">
                    </div>
                    <div class="col-md-6">
                        <label for="realName" class="form-label">真实姓名</label>
                        <input type="text" class="form-control" id="realName">
                    </div>
                    <div class="col-md-6">
                        <label for="phone" class="form-label">电话</label>
                        <input type="text" class="form-control" id="phone">
                    </div>
                    <div class="col-md-6">
                        <label for="role" class="form-label">角色</label>
                        <select class="form-select" id="role">
                            <option value="admin">管理员</option>
                            <option value="courier">快递员</option>
                            <option value="user">普通用户</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label for="userStatus" class="form-label">状态</label>
                        <select class="form-select" id="userStatus">
                            <option value="1">启用</option>
                            <option value="0">禁用</option>
                        </select>
                    </div>
                    <div class="col-md-12">
                        <button type="button" class="btn btn-primary" onclick="submitUserForm()">提交</button>
                        <button type="button" class="btn btn-secondary" onclick="hideUserForm()">取消</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let currentPage = 1;
        const pageSize = 10;
        let currentUser = null; // 当前登录用户
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 检查本地存储中的登录状态
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                try {
                    currentUser = JSON.parse(savedUser);
                    showSystemContent();
                } catch (e) {
                    console.error('解析用户信息失败:', e);
                }
            }
        });
        
        // 登录表单提交
        function submitLoginForm() {
            const username = document.getElementById('loginUsername').value;
            const password = document.getElementById('loginPassword').value;
            const loginMessage = document.getElementById('loginMessage');
            
            if (!username || !password) {
                loginMessage.textContent = '请输入用户名和密码';
                return;
            }
            
            axios.post('/api/login', {
                username: username,
                password: password
            })
            .then(function (response) {
                if (response.data && response.data.success) {
                    // 登录成功
                    currentUser = response.data.userInfo;
                    // 保存用户信息到本地存储
                    localStorage.setItem('currentUser', JSON.stringify(currentUser));
                    showSystemContent();
                } else {
                    // 登录失败
                    loginMessage.textContent = response.data ? response.data.message : '登录失败';
                }
            })
            .catch(function (error) {
                console.error('登录请求失败:', error);
                loginMessage.textContent = '登录请求失败，请稍后重试';
            });
        }
        
        // 显示系统内容
        function showSystemContent() {
            document.getElementById('loginFormContainer').style.display = 'none';
            document.getElementById('systemContent').style.display = 'block';
            document.getElementById('currentUser').textContent = 
                `当前用户: ${currentUser.username} (${getRoleText(currentUser.role)})`;
            
            // 根据用户角色控制功能显示
            applyRolePermissions();
            
            // 刷新快递列表
            refreshPackageList();
            
            // 如果是管理员，刷新用户列表
            if (currentUser.role === 'admin') {
                refreshUserList();
            }
        }
        
        // 应用角色权限
        function applyRolePermissions() {
            // 重置所有功能为可见/可用
            document.getElementById('userManagementNav').style.display = 'block';
            document.querySelector('button[onclick="showUserForm()"]').style.display = 'inline-block';
            document.querySelector('button[onclick="refreshUserList()"]').style.display = 'inline-block';
            
            // 根据角色控制权限
            switch(currentUser.role) {
                case 'admin':
                    // 管理员：拥有所有权限
                    break;
                case 'courier':
                    // 快递员：不能管理用户
                    document.getElementById('userManagementNav').style.display = 'none';
                    break;
                case 'user':
                    // 普通用户：只能查看快递信息，不能管理用户
                    document.getElementById('userManagementNav').style.display = 'none';
                    document.querySelector('button[onclick="showPackageForm()"]').style.display = 'none';
                    break;
                default:
                    // 未知角色：仅显示基本信息
                    document.getElementById('userManagementNav').style.display = 'none';
                    break;
            }
        }
        
        // 退出登录
        function logout() {
            currentUser = null;
            localStorage.removeItem('currentUser');
            document.getElementById('systemContent').style.display = 'none';
            document.getElementById('loginFormContainer').style.display = 'block';
            document.getElementById('loginForm').reset();
            document.getElementById('loginMessage').textContent = '';
        }
        
        // 获取角色文本
        function getRoleText(role) {
            switch(role) {
                case 'admin':
                    return '管理员';
                case 'courier':
                    return '快递员';
                case 'user':
                    return '普通用户';
                default:
                    return '未知角色';
            }
        }
        
        // 刷新快递列表
        function refreshPackageList() {
            axios.get('/api/package')
                .then(function (response) {
                    renderPackageList(response.data);
                })
                .catch(function (error) {
                    console.error('获取快递列表失败:', error);
                    alert('获取快递列表失败，请稍后重试');
                });
        }
        
        // 刷新用户列表
        function refreshUserList() {
            axios.get('/api/user')
                .then(function (response) {
                    renderUserList(response.data);
                })
                .catch(function (error) {
                    console.error('获取用户列表失败:', error);
                    alert('获取用户列表失败，请稍后重试');
                });
        }
        
        // 渲染快递列表
        function renderPackageList(packages) {
            const tableBody = document.getElementById('packageTableBody');
            tableBody.innerHTML = '';
            
            if (packages.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="7" class="text-center">暂无快递数据</td></tr>';
                return;
            }
            
            packages.forEach(pkg => {
                const statusClass = getStatusClass(pkg.status);
                const row = `
                    <tr>
                        <td>${pkg.id}</td>
                        <td>${pkg.trackingNumber}</td>
                        <td>${pkg.senderName || '-'}</td>
                        <td>${pkg.receiverName}</td>
                        <td><span class="status-badge ${statusClass}">${pkg.status}</span></td>
                        <td>${formatDateTime(pkg.createTime)}</td>
                        <td>${formatDateTime(pkg.signTime) || '-'}</td>
                        <td>${pkg.signPerson || '-'}</td>
                        <td>
                            <button class="btn btn-sm btn-info" onclick="editPackage(${pkg.id})">编辑</button>
                            <button class="btn btn-sm btn-danger" onclick="deletePackage(${pkg.id})">删除</button>
                            ${pkg.status === '已入库' ? `<button class="btn btn-sm btn-primary" onclick="outStorage(${pkg.id})">出库</button>` : ''}
                            <button class="btn btn-sm btn-success mr-1" onclick="signForPackage(${pkg.id})">签收</button>
                            <button class="btn btn-sm btn-primary" onclick="signForPackageWithPerson(${pkg.id})">签收(带信息)</button>
                        </td>
                    </tr>
                `;
                tableBody.innerHTML += row;
            });
        }
        
        // 渲染用户列表
        function renderUserList(users) {
            const tableBody = document.getElementById('userTableBody');
            tableBody.innerHTML = '';
            
            if (users.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="7" class="text-center">暂无用户数据</td></tr>';
                return;
            }
            
            users.forEach(user => {
                const statusText = user.status === 1 ? '启用' : '禁用';
                const statusClass = user.status === 1 ? 'text-success' : 'text-danger';
                const row = `
                    <tr>
                        <td>${user.id}</td>
                        <td>${user.username}</td>
                        <td>${user.realName || '-'}</td>
                        <td>${user.phone || '-'}</td>
                        <td>${user.role}</td>
                        <td class="${statusClass}">${statusText}</td>
                        <td>
                            <button class="btn btn-sm btn-info" onclick="editUser(${user.id})">编辑</button>
                            <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id})">删除</button>
                            <button class="btn btn-sm btn-warning" onclick="toggleUserStatus(${user.id}, ${user.status})">${user.status === 1 ? '禁用' : '启用'}</button>
                        </td>
                    </tr>
                `;
                tableBody.innerHTML += row;
            });
        }
        
        // 根据状态获取CSS类名
        function getStatusClass(status) {
            switch (status) {
                case '已入库':
                    return 'in-storage';
                case '已出库':
                    return 'out-storage';
                case '已签收':
                    return 'signed';
                default:
                    return 'other';
            }
        }
        
        // 格式化日期时间
        function formatDateTime(dateTime) {
            if (!dateTime) return '';
            const date = new Date(dateTime);
            return date.toLocaleString('zh-CN');
        }
        
        // 显示快递表单
        function showPackageForm() {
            document.getElementById('formTitle').textContent = '新增快递';
            document.getElementById('packageId').value = '';
            document.getElementById('packageFormData').reset();
            document.getElementById('packageForm').style.display = 'block';
            document.getElementById('packageList').style.display = 'none';
        }
        
        // 隐藏快递表单
        function hidePackageForm() {
            document.getElementById('packageForm').style.display = 'none';
            document.getElementById('packageList').style.display = 'block';
        }
        
        // 提交快递表单
        function submitPackageForm() {
            const id = document.getElementById('packageId').value;
            const packageData = {
                trackingNumber: document.getElementById('trackingNumber').value,
                status: document.getElementById('status').value,
                senderName: document.getElementById('senderName').value,
                senderPhone: document.getElementById('senderPhone').value,
                receiverName: document.getElementById('receiverName').value,
                receiverPhone: document.getElementById('receiverPhone').value,
                receiverAddress: document.getElementById('receiverAddress').value,
                remark: document.getElementById('remark').value
            };
            
            if (id) {
                // 编辑快递
                axios.put('/api/package', packageData)
                    .then(function (response) {
                        if (response.data) {
                            alert('快递信息更新成功');
                            hidePackageForm();
                            refreshPackageList();
                        } else {
                            alert('快递信息更新失败');
                        }
                    })
                    .catch(function (error) {
                        console.error('更新快递信息失败:', error);
                        alert('更新快递信息失败，请稍后重试');
                    });
            } else {
                // 新增快递
                axios.post('/api/package', packageData)
                    .then(function (response) {
                        if (response.data) {
                            alert('快递添加成功');
                            hidePackageForm();
                            refreshPackageList();
                        } else {
                            alert('快递添加失败');
                        }
                    })
                    .catch(function (error) {
                        console.error('添加快递失败:', error);
                        alert('添加快递失败，请稍后重试');
                    });
            }
        }
        
        // 编辑快递
        function editPackage(id) {
            // 只有管理员和快递员可以编辑快递
            if (currentUser.role !== 'admin' && currentUser.role !== 'courier') {
                alert('您没有权限执行此操作');
                return;
            }
            
            axios.get(`/api/package/${id}`)
                .then(function (response) {
                    const pkg = response.data;
                    document.getElementById('formTitle').textContent = '编辑快递';
                    document.getElementById('packageId').value = pkg.id;
                    document.getElementById('trackingNumber').value = pkg.trackingNumber;
                    document.getElementById('status').value = pkg.status || '已入库';
                    document.getElementById('senderName').value = pkg.senderName || '';
                    document.getElementById('senderPhone').value = pkg.senderPhone || '';
                    document.getElementById('receiverName').value = pkg.receiverName;
                    document.getElementById('receiverPhone').value = pkg.receiverPhone;
                    document.getElementById('receiverAddress').value = pkg.receiverAddress || '';
                    document.getElementById('remark').value = pkg.remark || '';
                    
                    document.getElementById('packageForm').style.display = 'block';
                    document.getElementById('packageList').style.display = 'none';
                })
                .catch(function (error) {
                    console.error('获取快递信息失败:', error);
                    alert('获取快递信息失败，请稍后重试');
                });
        }
        
        // 删除快递
        function deletePackage(id) {
            // 只有管理员可以删除快递
            if (currentUser.role !== 'admin') {
                alert('您没有权限执行此操作');
                return;
            }
            
            if (confirm('确定要删除这个快递吗？')) {
                axios.delete(`/api/package/${id}`)
                    .then(function (response) {
                        if (response.data) {
                            alert('快递删除成功');
                            refreshPackageList();
                        } else {
                            alert('快递删除失败');
                        }
                    })
                    .catch(function (error) {
                        console.error('删除快递失败:', error);
                        alert('删除快递失败，请稍后重试');
                    });
            }
        }
        
        // 快递出库
        function outStorage(id) {
            axios.post(`/api/package/out/${id}`)
                .then(function (response) {
                    if (response.data) {
                        alert('快递出库成功');
                        refreshPackageList();
                    } else {
                        alert('快递出库失败，可能已经出库或状态不正确');
                    }
                })
                .catch(function (error) {
                    console.error('快递出库失败:', error);
                    alert('快递出库失败，请稍后重试');
                });
        }
        
        // 快递签收
                    function signForPackage(id) {
                        axios.post(`/api/package/sign/${id}`)
                            .then(function (response) {
                                if (response.data) {
                                    alert('快递签收成功');
                                    refreshPackageList();
                                } else {
                                    alert('快递签收失败');
                                }
                            })
                            .catch(function (error) {
                                console.error('快递签收失败:', error);
                                alert('快递签收失败，请稍后重试');
                            });
                    }
                    
                    // 带签收人信息的快递签收
                    function signForPackageWithPerson(id) {
                        const signPerson = prompt('请输入实际签收人姓名：');
                        if (signPerson) {
                            axios.post(`/api/package/sign/${id}/withPerson`, { signPerson })
                                .then(function (response) {
                                    if (response.data) {
                                        alert('快递签收成功，已记录签收人信息');
                                        refreshPackageList();
                                    } else {
                                        alert('快递签收失败');
                                    }
                                })
                                .catch(function (error) {
                                    console.error('快递签收失败:', error);
                                    alert('快递签收失败，请稍后重试');
                                });
                        }
                    }
        
        // 根据快递单号查询
        function searchByTrackingNumber() {
            const trackingNumber = document.getElementById('trackingNumberQuery').value.trim();
            if (trackingNumber) {
                axios.get(`/api/package/tracking/${trackingNumber}`)
                    .then(function (response) {
                        renderPackageList(response.data);
                    })
                    .catch(function (error) {
                        console.error('查询快递失败:', error);
                        alert('查询快递失败，请稍后重试');
                    });
            } else {
                refreshPackageList();
            }
        }
        
        // 根据状态查询
        function searchByStatus() {
            const status = document.getElementById('statusQuery').value;
            if (status) {
                axios.get(`/api/package/status/${status}`)
                    .then(function (response) {
                        renderPackageList(response.data);
                    })
                    .catch(function (error) {
                        console.error('查询快递失败:', error);
                        alert('查询快递失败，请稍后重试');
                    });
            } else {
                refreshPackageList();
            }
        }
        
        // 显示用户表单
        function showUserForm() {
            document.getElementById('userFormTitle').textContent = '新增用户';
            document.getElementById('userId').value = '';
            document.getElementById('userFormData').reset();
            document.getElementById('userForm').style.display = 'block';
            document.getElementById('userList').style.display = 'none';
        }
        
        // 隐藏用户表单
        function hideUserForm() {
            document.getElementById('userForm').style.display = 'none';
            document.getElementById('userList').style.display = 'block';
        }
        
        // 提交用户表单
        function submitUserForm() {
            // 只有管理员可以管理用户
            if (currentUser.role !== 'admin') {
                alert('您没有权限执行此操作');
                return;
            }
            
            const userId = document.getElementById('userId').value;
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const realName = document.getElementById('realName').value;
            const phone = document.getElementById('phone').value;
            const role = document.getElementById('role').value;
            const status = document.getElementById('userStatus').value;

            const userData = {
                username: username,
                password: password,
                realName: realName,
                phone: phone,
                role: role,
                status: parseInt(status)
            };
            
            if (userId) {
                // 编辑用户
                axios.put('/api/user', userData)
                    .then(function (response) {
                        if (response.data) {
                            alert('用户信息更新成功');
                            hideUserForm();
                            refreshUserList();
                        } else {
                            alert('用户信息更新失败');
                        }
                    })
                    .catch(function (error) {
                        console.error('更新用户信息失败:', error);
                        alert('更新用户信息失败，请稍后重试');
                    });
            } else {
                // 新增用户
                axios.post('/api/user', userData)
                    .then(function (response) {
                        if (response.data) {
                            alert('用户添加成功');
                            hideUserForm();
                            refreshUserList();
                        } else {
                            alert('用户添加失败');
                        }
                    })
                    .catch(function (error) {
                        console.error('添加用户失败:', error);
                        alert('添加用户失败，请稍后重试');
                    });
            }
        }
        
        // 编辑用户
        function editUser(id) {
            // 只有管理员可以编辑用户
            if (currentUser.role !== 'admin') {
                alert('您没有权限执行此操作');
                return;
            }
            
            axios.get(`/api/user/${id}`)
                .then(function (response) {
                    const user = response.data;
                    document.getElementById('userFormTitle').textContent = '编辑用户';
                    document.getElementById('userId').value = user.id;
                    document.getElementById('username').value = user.username;
                    document.getElementById('password').value = ''; // 不显示密码
                    document.getElementById('realName').value = user.realName || '';
                    document.getElementById('phone').value = user.phone || '';
                    document.getElementById('role').value = user.role || 'user';
                    document.getElementById('userStatus').value = user.status || 1;
                    
                    document.getElementById('userForm').style.display = 'block';
                    document.getElementById('userList').style.display = 'none';
                })
                .catch(function (error) {
                    console.error('获取用户信息失败:', error);
                    alert('获取用户信息失败，请稍后重试');
                });
        }
        
        // 删除用户
        function deleteUser(id) {
            // 只有管理员可以删除用户
            if (currentUser.role !== 'admin') {
                alert('您没有权限执行此操作');
                return;
            }
            
            if (confirm('确定要删除这个用户吗？')) {
                axios.delete(`/api/user/${id}`)
                    .then(function (response) {
                        if (response.data) {
                            alert('用户删除成功');
                            refreshUserList();
                        } else {
                            alert('用户删除失败');
                        }
                    })
                    .catch(function (error) {
                        console.error('删除用户失败:', error);
                        alert('删除用户失败，请稍后重试');
                    });
            }
        }
        // 切换用户状态
        function toggleUserStatus(id, currentStatus) {
            // 只有管理员可以切换用户状态
            if (currentUser.role !== 'admin') {
                alert('您没有权限执行此操作');
                return;
            }
            
            const newStatus = currentStatus === 1 ? 0 : 1;
            const actionText = newStatus === 1 ? '启用' : '禁用';
            
            if (confirm(`确定要${actionText}这个用户吗？`)) {
                axios.put(`/api/user/status/${id}/${newStatus}`)
                    .then(function (response) {
                        if (response.data) {
                            alert(`用户${actionText}成功`);
                            refreshUserList();
                        } else {
                            alert(`用户${actionText}失败`);
                        }
                    })
                    .catch(function (error) {
                        console.error(`用户${actionText}失败:`, error);
                        alert(`用户${actionText}失败，请稍后重试`);
                    });
            }
        }
    </script>
</body>
</html>